package de.slothsoft.wasbinich.android.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.res.Configuration;
import android.widget.Toast;
import de.slothsoft.wasbinich.core.WasBinIch;
import de.slothsoft.wasbinich.core.util.ExceptionUtil;

public final class ActivityUtil {

    private static Activity currentActivity;
    private static final List<Activity> allActivities = new ArrayList<Activity>();

    public static void reloadLocale(Activity activity, Locale newLocale) {
	Configuration config = new Configuration();
	config.locale = newLocale;
	activity.getBaseContext().getResources().updateConfiguration(config, null);
    }

    public static Activity getCurrentActivity() {
	return currentActivity;
    }

    public static void setCurrentActivity(Activity currentActivity) {
	ActivityUtil.currentActivity = currentActivity;
    }

    public static void addActivity(Activity activity) {
	allActivities.add(activity);
    }

    public static void removeActivity(Activity activity) {
	allActivities.remove(activity);
    }

    public static List<Activity> getAllActivities() {
	return allActivities;
    }

    public static void handleFatalException(final Activity activity, final Exception exception) {
	handleException(activity, exception);
	activity.runOnUiThread(new Runnable() {
	    @Override
	    public void run() {
		activity.setResult(Activity.RESULT_CANCELED);
		activity.finish();
	    }
	});
    }

    public static void handleException(final Activity activity, final Exception exception) {
	if (ExceptionUtil.isCancelledByUserException(exception)) {
	    if (WasBinIch.DEBUG) {
		System.err.println("The action was cancelled by the user!"); //$NON-NLS-1$
	    }
	} else {
	    if (WasBinIch.DEBUG) {
		exception.printStackTrace();
	    }
	    activity.runOnUiThread(new Runnable() {
		@Override
		public void run() {
		    String message = ExceptionUtil.getErrorMessage(exception);
		    Toast toast = Toast.makeText(activity.getBaseContext(), message, Toast.LENGTH_SHORT);
		    toast.show();
		}
	    });
	}
    }

    private ActivityUtil() {
	// hide me
    }
}
